package com.example.learningnote.apis;

import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import com.example.learningnote.params.LoginParams;
import com.example.learningnote.utils.Http;
import com.example.learningnote.response.UserResponse;
import com.example.learningnote.utils.HttpResult;
import com.google.gson.Gson;

import java.io.IOException;
import java.util.Map;


public class LoginApi {
    private static final Gson gson = new Gson();

    public static void fetchLoginHandle(LoginParams params, Context context, Handler callbackHandle) {
        new Thread(() -> {
            try {
                Map<String, Object> response = Http.post("login", params.toMap(), Map.class, context);
                if (response.get("success") != null && (Boolean) response.get("success")) {
                    String dataJosn = gson.toJson(response.get("data"));
                    UserResponse userResponse = gson.fromJson(dataJosn, UserResponse.class);
                    Message msg = Message.obtain();
                    msg.what = 1;
                    msg.obj = userResponse;
                    callbackHandle.sendMessage(msg);
                }else{
                    sendErrorMessage(callbackHandle , "登录接口格式错误");
                }

            } catch (IOException e) {
                Log.e("HTTP", "登录接口失败" + e.getMessage(), e);
                sendErrorMessage(callbackHandle , "登录接口失败");
            }
        }).start();
    }

    private static void sendErrorMessage(Handler handler, String error) {
        Message msg = Message.obtain();
        msg.what = 0; // 错误消息
        msg.obj = error;
        handler.sendMessage(msg);
    }


    public static LoginResult fetchLoginAsync(LoginParams params, Context context) {
        try {
            Map<String, Object> response = Http.post("login", params.toMap(), Map.class, context);
            if (response.get("success") != null && (Boolean) response.get("success")) {
                String dataJson = gson.toJson(response.get("data"));
                UserResponse userResponse = gson.fromJson(dataJson, UserResponse.class);
                return new LoginResult(true, userResponse, null);
            } else {
                return new LoginResult(false, null, "登录接口格式错误");
            }
        } catch (IOException e) {
            Log.e("HTTP", "登录接口失败" + e.getMessage(), e);
            return new LoginResult(false, null, "登录接口失败");
        }
    }

    public static class LoginResult extends HttpResult<UserResponse> {
        public LoginResult(boolean success, UserResponse userResponse, String error) {
            super(success, userResponse, error);
        }

        public UserResponse getUserResponse() {
            return getData();
        }
    }

}